package com.example.shopping.service;

import com.example.shopping.entity.Order;
import com.example.shopping.entity.dto.OrderDTO;
import com.example.shopping.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService{
    @Autowired
    private OrderRepository orderRepository;

    @Override
    public List<OrderDTO> findAllOrdersWithUserInfoAndGoodsInfo() {
        return orderRepository.findOrderDTOs();
    }

    @Override
    public Page<OrderDTO> queryOrders(String username, String goodsname, String mailingaddress, String rphone, String receiver, LocalDate buytimebegin, LocalDate buytimeend, int pageNo, int pageSize) {
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);

        LocalDateTime begin = null;
        if (buytimebegin != null){
            begin=buytimebegin.atStartOfDay();
        }

        LocalDateTime end = null;
        if (buytimeend != null){
            end=buytimeend.atTime(23, 59, 59);
        }
        return orderRepository.findOrdersWithCriteria(username, goodsname, mailingaddress,
                rphone, receiver, begin, end, pageable);
    }

    @Override
    public Order createOrder(int uid, String gid, Integer quantity, Double money, LocalDateTime buytime, String rphone, String mailingaddress, String receiver, Float price) {
        // 创建订单对象
        Order order = new Order();
        order.setUid(uid);
        order.setGid(gid);
        order.setPrice(price);
        order.setQuantity(quantity);
        order.setReceiver(receiver);
        order.setRphone(rphone);
        order.setMailingaddress(mailingaddress);
        order.setMoney(money);
        order.setBuytime(buytime);
        orderRepository.save(order);
        return order;
    }

    @Override
    public List<OrderDTO> findOrdersByUid(int uid) {
        return orderRepository.findOrdersByUid(uid);
    }
}
